/**
 * Created by user on 3/27/19.
 */
class MediaManager {
  prepareUrl = {
    video: 'http://1252139118.vod2.myqcloud.com/8e24db68vodtransgzp1252139118/6d0eed8f5285890784401178427/v.f20.mp4',
    audio: 'https://img.live.chinatravelacademy.com/upload/2019/02/27/G6MdZVsjJB9mP7uMM8n0EjgtbvCkHsNFzIllp3u1.mp3'
  }
  video = document.getElementById('htmlVideo')
  audio = document.getElementById('htmlAudio')
  prepareMedia = (callback) => {
    var audioDone = false
    var videoDone = false
    const checkDone = () => {
      if (audioDone && videoDone) {
        callback && callback()
      }
    }
    const videoPlaying = () => {
      this.video.pause()
      videoDone = true
      this.video.removeEventListener('play', videoPlaying)
      checkDone()
    }
    const audioPlaying = () => {
      this.audio.pause()
      audioDone = true
      this.audio.removeEventListener('play', audioPlaying)
      checkDone()
    }
    this.video.style.display = 'none'
    this.audio.style.display = 'none'
    this.video.addEventListener('play', videoPlaying)
    this.audio.addEventListener('play', audioPlaying)
    this.video.src = this.prepareUrl.video
    this.audio.src = this.prepareUrl.audio
    this.video.play()
      // .catch((err) => {
      // // callback && callback(false)
      // console.log('video err', err)})
    this.audio.play()
      // .catch((err) => {
      // // callback && callback(false)
      // console.log('audio err', err)})
  }
  playSingleVideo = (url, playCallback, endCallback) => {
    var loaded = false
    this.video.src = url
    this.video.style.display = 'block'
    function videoTimeUpdate() {
      if (this.video.currentTime > 0 && !loaded) {
        loaded = true
        this.video.removeEventListener('timeupdate', videoTimeUpdate)
        playCallback && playCallback()
      }
    }
    function videoEnded() {
      this.video.style.display = 'none'
      this.video.removeEventListener('ended', videoEnded)
      endCallback && endCallback()
    }
    this.video.addEventListener('timeupdate', videoTimeUpdate)
    this.video.addEventListener('ended', videoEnded)
    this.video.play()
  }
  playSingleVoice = (url, playCallback, endCallback) => {
    var loaded = false
    this.audio.src = url
    function audioTimeUpdate() {
      if (this.audio.currentTime > 0 && !loaded) {
        loaded = true
        this.audio.removeEventListener('timeupdate', audioTimeUpdate)
        playCallback && playCallback()
      }
    }
    function audioEnded() {
      this.audio.removeEventListener('ended', audioEnded)
      endCallback && endCallback()
    }
    this.audio.addEventListener('timeupdate', audioTimeUpdate)
    this.audio.addEventListener('ended', audioEnded)
    this.audio.play()
  }
}

module.exports = new MediaManager()
